package com.gangquan360.smartadmin.module.region;

import java.util.Collections;
import java.util.List;

import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.gangquan360.smartadmin.common.domain.ResponseDTO;
import com.gangquan360.smartadmin.module.region.domain.RegionDTO;
import com.gangquan360.smartadmin.module.region.domain.RegionEntity;
import com.gangquan360.smartadmin.util.SmartTreeUtil;
import com.google.common.collect.Lists;

import lombok.extern.slf4j.Slf4j;

@Service
@Slf4j
public class RegionService {

	@Autowired
	private RegionDao regionDao;
	
	private static List<RegionDTO> regionTree = Lists.newArrayList();
	
	
	public ResponseDTO<List<RegionDTO>> getRegionTree() {
		if (CollectionUtils.isNotEmpty(regionTree)) {
			return ResponseDTO.succData(regionTree);
		}
		Wrapper<RegionEntity> wrapper = new EntityWrapper<>();
		List<RegionEntity> selectList = regionDao.selectList(wrapper);
		List<RegionDTO> createTree = SmartTreeUtil.createTree(RegionDTO.class, selectList, 0L, RegionEntity::getPid, region -> region.getId(),
				(RegionDTO regionDto, List<RegionDTO> regionDtoList) -> {
					regionDto.setChildren(regionDtoList);
				});
		log.info("regionTree => {}", createTree);
		regionTree = createTree;
		return ResponseDTO.succData(createTree);
	}
}
